import {useState, useEffect} from 'react'
import styled from 'styled-components'
import { Navbar } from "../modules/Navbar"

const Table = styled.table`
  border: 1px solid;
  & th, td {
    border: 1px solid;
  }
`

interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}
export default function TodoListPage () {
  const [todos, setTodos] = useState<Todo[]>([])

  const loadData = () => {
    fetch('https://jsonplaceholder.typicode.com/todos')
    .then((response) => {
      if (response.status !== 200 || !response.ok) throw new Error('Response fail');
      else return response.json();
    })
    .then((body) =>{
      if (!!body.length) setTodos(body)
    })
    .catch((err) => {
      console.error(err)
    })
  }
  
  useEffect(() => {
    loadData()
  }, [])

  return (
    <main>
      <Navbar />
      <h1>Todo Page</h1>
      <Table>
        <tbody>
          <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Status</th>
          </tr>

          { todos.map((item, index) => (
            <tr key={index}>
              <td>{item.id}</td>
              <td>{item.title}</td>
              <td>{item.completed ? '✅':'🕙'}</td>
            </tr>
          )) }
        </tbody>

      </Table>

    </main>
  )
}
